<!DOCTYPE html>
<html>

<head>
  <title>前端Word编辑器</title>
  <script src="https://unpkg.com/docx@7.8.1/build/index.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/docx-parser@1.0.0/dist/docx-parser.min.js"></script>
  <style>
    #editor {
      width: 100%;
      height: 500px;
      border: 1px solid #ccc;
      padding: 10px;
      overflow-y: auto;
    }

    .toolbar {
      margin-bottom: 10px;
    }

    button {
      margin-right: 5px;
    }
  </style>
</head>

<body>
  <div class="toolbar">
    <input type="file" id="fileInput" accept=".docx" />
    <button id="downloadBtn">下载文档</button>
    <button id="boldBtn">加粗</button>
    <button id="insertBtn">插入文本</button>
  </div>
  <div id="editor" contenteditable="true"></div>

  <script>
    let currentDoc = null;
    let docContent = [];

    // 加载文档
    document.getElementById('fileInput').addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      try {
        const arrayBuffer = await file.arrayBuffer();
        const content = await docx.parse(arrayBuffer);
        docContent = content;

        // 显示在编辑器中
        const editor = document.getElementById('editor');
        editor.innerHTML = content.paragraphs.map(p =>
          `<p style="font-weight: ${p.bold ? 'bold' : 'normal'}">${p.text}</p>`
        ).join('');

        currentDoc = await docx.Document.load(arrayBuffer);
      } catch (err) {
        console.error("解析失败:", err);
      }
    });

    // 下载文档
    document.getElementById('downloadBtn').addEventListener('click', async () => {
      if (!currentDoc) {
        // 创建新文档
        currentDoc = new docx.Document({
          sections: [{
            properties: {},
            children: getParagraphsFromEditor()
          }]
        });
      }

      const blob = await docx.Packer.toBlob(currentDoc);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'edited_document.docx';
      a.click();
      URL.revokeObjectURL(url);
    });

    // 加粗选中文本
    document.getElementById('boldBtn').addEventListener('click', () => {
      document.execCommand('bold', false, null);
    });

    // 插入文本
    document.getElementById('insertBtn').addEventListener('click', () => {
      const selection = window.getSelection();
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        const newNode = document.createElement('span');
        newNode.textContent = '【插入文本】';
        range.insertNode(newNode);
      }
    });

    // 从编辑器获取段落
    function getParagraphsFromEditor() {
      const editor = document.getElementById('editor');
      const paragraphs = [];

      editor.querySelectorAll('p').forEach(p => {
        paragraphs.push(new docx.Paragraph({
          children: [new docx.TextRun({
            text: p.textContent,
            bold: window.getComputedStyle(p).fontWeight === 'bold'
          })]
        }));
      });

      return paragraphs;
    }
  </script>
</body>

</html>